﻿using System;
using System.Collections.Specialized;
using System.Text;
using System.Net;
using System.Net.Mail;

namespace MailHelper
{
    public class MailOper
    {
        #region Field
        private string _host;//SMTP服务器
        private int _port;//SMTP端口号，通常为25
        private string _account;//登录服务器的帐号
        private string _pwd;//登录服务器密码
        public static SmtpClient sc;//详见 http://msdn.microsoft.com/zh-cn/library/system.net.mail.smtpclient(VS.80).aspx
        #endregion

        #region Constraction
        /// <summary>
        /// Build MailOper By Config
        /// </summary>
        /// <param name="apps"></param>
        public MailOper(NameValueCollection apps)
        {
            _host = apps["SmtpServer"];
            _port = int.TryParse(apps["SmtpPort"], out _port) ? _port : 25;
            _account = apps["SmtpUserName"];
            _pwd = apps["SmtpUserPwd"];
            InitOper();
        }

        public MailOper(string host, int port, string account, string pwd)
        {
            _host = host;
            _port = port;
            _account = account;
            _pwd = pwd;
            InitOper();
        }
        #endregion

        #region Methord
        private void InitOper()
        {
            if (null == sc)
            {
                sc = new SmtpClient(_host, _port);
                sc.Credentials = new NetworkCredential(_account, _pwd);
                sc.DeliveryMethod = SmtpDeliveryMethod.Network;                
            }
        }
        /// <summary>
        /// 发送Mail
        /// </summary>
        /// <param name="mailTo"></param>
        /// <param name="title"></param>
        /// <param name="body"></param>
        /// <param name="isHTML"></param>
        public void SendMail(string mailTo, string mailfrom, string title, string body, bool isHTML)
        {
            MailMessage msg = new MailMessage(mailfrom, mailTo, title, body);
            msg.BodyEncoding = Encoding.UTF8;
            msg.IsBodyHtml = isHTML;
            sc.Send(msg);
        }
        #endregion
    }
}
